<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入销售金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="销售单号" align="center" prop="orderNo" />
      <el-table-column label="客户名称" align="center" prop="customerId">
        <template slot-scope="scope">
          <span>{{ scope.row.customerName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货仓库" align="center" prop="warehouse" />
      <el-table-column label="销售金额" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.totalAmount ? '¥' + scope.row.totalAmount.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2}) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-button 
            :type="getStatusButtonType(scope.row.status)"
            size="mini"
            @click="toggleOrderStatus(scope.row)"
            v-hasPermi="['system:order:edit']"
            :disabled="scope.row.status === 4"
          >
            {{ getStatusText(scope.row.status) }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="系统自动生成" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="发货仓库" prop="warehouse">
          <el-input v-model="form.warehouse" placeholder="请输入发货仓库名称" />
        </el-form-item>
        <el-form-item label="销售金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="自动计算" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        
        <!-- 商品搜索区域 -->
        <div class="product-search-section">
          <el-form-item label="搜索商品">
            <el-input 
              v-model="productSearch.keyword" 
              placeholder="请输入商品名称或编号" 
              style="width: 250px; margin-right: 10px;"
            />
            <el-button type="primary" @click="searchProduct">搜索</el-button>
          </el-form-item>
          
          <!-- 搜索结果 -->
          <div v-if="productSearch.result" class="search-result">
            <el-row type="flex" justify="space-between">
              <div style="display: flex; align-items: center; flex-wrap: nowrap;">
                <div style="white-space: nowrap;">商品名称：{{ productSearch.result.name }}</div>
                <div style="margin-left: 15px; white-space: nowrap;">单价：¥{{ Number(productSearch.result.sellingPrice || 0).toFixed(2) }}</div>
              </div>
              <el-col :span="12" style="display: flex; align-items: center; justify-content: flex-end;">
                <el-input-number 
                    v-model="productQuantity" 
                    :min="1" 
                    style="width: 150px; margin-right: 10px;"
                  />
                <el-button type="success" @click="addProductToOrder">添加商品</el-button>
              </el-col>
            </el-row>
          </div>

        </div>
        
        <!-- 已添加商品列表 -->
        <div class="product-list-section">
          <h4>已添加商品</h4>
          <el-table 
            v-if="orderItems.length > 0" 
            :data="orderItems" 
            border 
            style="width: 100%"
          >
            <el-table-column prop="productName" label="商品名称" width="" />
            <el-table-column prop="sellingPrice" label="单价" width="100" align="right" />
            <el-table-column prop="quantity" label="数量" width="100" align="center" />
            <el-table-column label="小计" width="120" align="right">
              <template slot-scope="scope">
                {{ scope.row.sellingPrice && scope.row.quantity ? (Number(scope.row.sellingPrice) * Number(scope.row.quantity)).toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="removeProduct(scope.$index)"
                  style="color: #f56c6c;"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="no-data">暂无商品</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order"
import { listCustomer, getCustomer } from "@/api/system/customer"
import { listProduct, getProduct } from "@/api/system/product"
import { listItem, addItem, delItem } from "@/api/system/item"

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        customerName: null,
        warehouse: null,
        totalAmount: null,
        status: null,
      },
      // 客户名称映射
      customerNameMap: {},
      // 表单参数
      form: {
        customerName: ''
      },
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "销售单号不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        warehouse: [
          { required: true, message: "发货仓库不能为空", trigger: "change" }
        ],
        totalAmount: [
          { required: true, message: "销售总金额不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态：1=待付款，2=已付款，3=已发货，4=完成不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
      },
      // 商品搜索
      productSearch: {
        keyword: '',
        result: null
      },
      // 销售单商品明细
      orderItems: [],
      // 商品数量
      productQuantity: 1,
      // 提交状态标志，防止重复提交
      submitting: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询销售单列表 */
    getList() {
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        // 加载客户名称
        this.loadCustomerNames()
        this.total = response.total
        this.loading = false
      })
    },
    
    /** 加载客户名称 */
    loadCustomerNames() {
      if (this.orderList.length > 0) {
        // 获取所有客户ID
        const customerIds = [...new Set(this.orderList.map(item => item.customerId).filter(id => id))]
        if (customerIds.length > 0) {
          // 使用正确的参数格式查询客户列表
          listCustomer({ ids: customerIds.join(',') }).then(response => {
            // 构建客户ID到客户名称的映射
            response.rows.forEach(customer => {
              this.customerNameMap[customer.id] = customer.name
            })
            // 使用Vue.set确保响应式更新
            this.orderList.forEach(order => {
              this.$set(order, 'customerName', this.customerNameMap[order.customerId] || '-')
            })
          })
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: null,
        customerId: null,
        warehouse: null,
        totalAmount: null,
        status: null,
        createBy: null,
        createTime: null
      }
      // 清空商品明细列表
      this.orderItems = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 生成销售单号 */
    generateOrderNo() {
      // 获取当前日期，使用完整格式：完整年份+月份+日期
      const now = new Date()
      const year = String(now.getFullYear()) // 取完整年份
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      
      // 生成3位随机序号，确保唯一性
      const sequence = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      
      // 格式：XS + 完整日期 + 3位序号，如：XS20241001001
      this.form.orderNo = `XS${year}${month}${day}${sequence}`
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加销售单"
      // 自动生成销售单号
      this.generateOrderNo()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data
        // 确保form有customerName属性
        this.$set(this.form, 'customerName', '')
        // 根据客户ID获取客户名称 - 使用缓存的客户名称映射，避免额外网络请求
        if (response.data.customerId) {
          // 优先从已加载的customerNameMap中获取客户名称
          const customerName = this.customerNameMap[response.data.customerId]
          if (customerName) {
            this.$set(this.form, 'customerName', customerName)
          } else {
            // 以防缓存中没有，使用getCustomer方法查询
            getCustomer(response.data.customerId).then(cusRes => {
              if (cusRes.data) {
                this.$set(this.form, 'customerName', cusRes.data.name)
                // 更新缓存
                this.$set(this.customerNameMap, response.data.customerId, cusRes.data.name)
            }
            })
          }
        }
        
        // 加载与该订单关联的商品明细（从order_item表中查询）
        listItem({ orderId: id }).then(itemResponse => {
          if (itemResponse.rows && itemResponse.rows.length > 0) {
            // 清空现有商品明细
            this.orderItems = []
            
            // 获取所有商品ID
            const productIds = [...new Set(itemResponse.rows.map(item => item.productId))]
            
            // 先创建临时商品明细数组
            const tempItems = itemResponse.rows.map(item => ({
              productId: item.productId,
              productName: `加载中...`, // 临时名称
              sellingPrice: item.sellingPrice || 0,
              quantity: item.quantity
            }))
            
            this.orderItems = tempItems
            
            // 调用商品API获取真实的商品名称
            if (productIds.length > 0) {
              listProduct({ ids: productIds.join(',') }).then(productResponse => {
                if (productResponse.rows && productResponse.rows.length > 0) {
                  // 构建商品ID到商品名称的映射
                  const productNameMap = {}
                  productResponse.rows.forEach(product => {
                    productNameMap[product.id] = product.name
                  })
                  
                  // 更新商品名称
                  this.orderItems.forEach(item => {
                    this.$set(item, 'productName', productNameMap[item.productId] || `未知商品`)
                  })
                } else {
                  // 如果没有找到商品信息，使用默认名称
                  this.orderItems.forEach(item => {
                    this.$set(item, 'productName', `未知商品`)
                  })
                }
              }).catch(() => {
                // 出错时使用默认名称
                this.orderItems.forEach(item => {
                  this.$set(item, 'productName', `未知商品`)
                })
              })
            }
            
            // 重新计算销售总金额
            this.calculateTotalAmount()
          } else {
            this.orderItems = []
            this.calculateTotalAmount()
          }
        }).catch(() => {
          this.$modal.msgError("加载商品明细失败")
        })
        
        this.open = true
        this.title = "修改销售单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 根据客户名称查找客户ID
          if (this.form.customerName) {
            listCustomer({ name: this.form.customerName }).then(cusRes => {
              if (cusRes.rows && cusRes.rows.length > 0) {
                // 将客户ID设置到表单中
                this.form.customerId = cusRes.rows[0].id
                this.submitOrderForm()
              } else {
                this.$modal.msgError("未找到该客户，请先添加客户信息")
              }
            })
          } else {
            this.submitOrderForm()
          }
        }
      })
    },
    
    /** 搜索商品 */
    searchProduct() {
      if (!this.productSearch.keyword) {
        this.$modal.msgWarning("请输入商品名称或编号")
        return
      }
      
      listProduct({ name: this.productSearch.keyword }).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 检查并确保price字段存在
          const product = response.rows[0]
          // 如果sellingPrice不存在或为0，尝试使用purchasePrice
          if (!product.sellingPrice || product.sellingPrice === 0) {
            product.sellingPrice = product.purchasePrice || 0
          }
          
          this.productSearch.result = product
        } else {
          this.productSearch.result = null
          this.$modal.msgError("未找到该商品")
        }
      })
    },
    
    /** 添加商品到订单 */
    addProductToOrder() {
      if (!this.productSearch.result) {
        this.$modal.msgWarning("请先搜索并选择商品")
        return
      }
      
      // 检查商品是否已在列表中
      const existingProduct = this.orderItems.find(item => item.productId === this.productSearch.result.id)
      if (existingProduct) {
        // 如果已存在，累加数量
        existingProduct.quantity += this.productQuantity
      } else {
        // 添加新商品
        const newProduct = {
          productId: this.productSearch.result.id,
          productName: this.productSearch.result.name,
          sellingPrice: Number(this.productSearch.result.sellingPrice || 0),
          quantity: this.productQuantity
        }
        this.orderItems.push(newProduct)
      }
      
      // 重置搜索结果和数量
      this.productSearch.result = null
      this.productSearch.keyword = ''
      this.productQuantity = 1
      
      // 计算销售总金额
      this.calculateTotalAmount()
    },
    

    
    /** 移除商品 */
    removeProduct(index) {
      this.orderItems.splice(index, 1)
      this.calculateTotalAmount()
    },
    
    /** 计算销售总金额 */
    calculateTotalAmount() {
      let totalAmount = 0
      for (const item of this.orderItems) {
        const quantity = Number(item.quantity || 0)
        const sellingPrice = Number(item.sellingPrice || 0)
        totalAmount += quantity * sellingPrice
      }
      this.form.totalAmount = totalAmount.toFixed(2)
    },
    
    /** 提交订单表单 */
    submitOrderForm() {
      // 防止重复提交
      if (this.submitting) {
        return
      }
      
      // 创建表单数据副本
      const submitData = { ...this.form }
      
      // 如果是新增订单，设置创建人和创建时间
      if (submitData.id == null) {
        const username = sessionStorage.getItem('username') || 'admin'
        submitData.createBy = username
        
        // 格式化日期为 yyyy-MM-dd HH:mm:ss
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        const day = String(now.getDate()).padStart(2, '0')
        const hours = String(now.getHours()).padStart(2, '0')
        const minutes = String(now.getMinutes()).padStart(2, '0')
        const seconds = String(now.getSeconds()).padStart(2, '0')
        
        submitData.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      this.submitting = true // 设置提交状态为true
      
      if (submitData.id != null) {
        // 修改订单
        updateOrder(submitData).then(response => {
          this.handleOrderItems(submitData.id)
        }).catch(() => {
          this.$modal.msgError("修改订单失败")
          this.submitting = false
        })
      } else {
        // 新增订单
        // 保存当前的orderItems到临时变量，确保在异步操作中数据不丢失
        const currentOrderItems = [...this.orderItems]
        
        addOrder(submitData).then(response => {
          // 更灵活地处理响应，避免因响应格式问题导致误判
          if (response && (response.code === 200 || response.code === '200')) {
            // 尝试获取订单ID，考虑更多可能的响应格式
            let orderId = null
            if (response.data && response.data.id) {
              orderId = response.data.id
            } else if (response.id) {
              orderId = response.id
            } else if (response.data) {
              // 尝试直接使用response.data作为订单ID
              orderId = response.data
            }
            
            // 如果订单ID仍然为null，尝试从响应的不同位置查找
            if (!orderId && response) {
              // 遍历响应对象的所有属性查找ID
              for (const key in response) {
                if (key.toLowerCase() === 'id' || key.toLowerCase().endsWith('id')) {
                  orderId = response[key]
                  break
                }
              }
            }
            
            if (orderId) {
              // 订单创建成功，继续处理商品明细
              this.handleOrderItems(orderId)
            } else {
              // 尝试根据订单号查询订单ID
              this.findOrderIdByOrderNo(submitData.orderNo)
            }
          } else {
            throw new Error(`订单创建失败: 响应状态码异常 (${response ? response.code : '无响应'})`)
          }
        }).catch(error => {
          // 更详细地分析错误类型
          let errorMessage = "添加订单过程中出现错误，请刷新列表确认是否已成功添加"
          
          if (error && error.message) {
            if (error.message.includes('Data too long for column')) {
              errorMessage = "订单号长度超过数据库限制，请刷新后重试"
            } else if (error.message.includes('Duplicate entry')) {
              errorMessage = "订单号重复，请刷新后重试"
            }
          }
          
          // 无论如何都显示提示并重置状态
          this.$modal.msgError(errorMessage)
          this.submitting = false
          
          // 延迟重新生成订单号，以便用户查看当前订单号
          setTimeout(() => {
            this.generateOrderNo()
          }, 2000)
        })
      }
    },
    
    /** 处理订单商品明细 */
    handleOrderItems(orderId) {
      // 如果是修改订单，先删除原有的商品明细
      if (this.form.id != null) {
        listItem({ orderId: this.form.id }).then(itemResponse => {
          if (itemResponse.rows && itemResponse.rows.length > 0) {
            // 获取所有要删除的商品明细ID
            const itemIds = itemResponse.rows.map(item => item.id)
            // 删除原有商品明细
            delItem(itemIds).then(() => {

              // 删除成功后添加新的商品明细
              this.addNewOrderItems(orderId)
            }).catch(() => {
              this.$modal.msgError("商品明细更新失败")
            })
          } else {
            // 没有原有商品明细，直接添加新的
            this.addNewOrderItems(orderId)
          }
        }).catch(() => {
          this.$modal.msgError("查询商品明细失败")
        })
      } else {
        // 新增订单直接添加商品明细
        this.addNewOrderItems(orderId)
      }
    },
    
    /** 根据订单号查询订单ID */
    findOrderIdByOrderNo(orderNo) {
      // 延迟查询，确保后端已经完成订单创建
      setTimeout(() => {
        listOrder({ orderNo: orderNo }).then(orderRes => {
          if (orderRes.rows && orderRes.rows.length > 0) {
            const foundOrder = orderRes.rows[0]
            const orderId = foundOrder.id
            
            if (orderId) {
              // 找到订单ID，继续处理商品明细
              this.handleOrderItems(orderId)
            } else {
              this.open = false
              this.getList()
              this.submitting = false
              this.$modal.msgWarning("订单添加请求已发送，但未能获取订单ID，请刷新列表确认")
            }
          } else {
            this.open = false
            this.getList()
            this.submitting = false
            this.$modal.msgWarning("订单添加请求已发送，请刷新列表确认是否已成功添加")
          }
        }).catch(() => {
          this.open = false
          this.getList()
          this.submitting = false
          this.$modal.msgWarning("订单添加请求已发送，请刷新列表确认是否已成功添加")
        })
      }, 1000) // 1秒延迟，给后端足够时间处理订单创建
    },
    
    /** 添加新的订单商品明细 */
    addNewOrderItems(orderId) {
      // 检查订单商品列表
      if (!this.orderItems || this.orderItems.length === 0) {
        this.$modal.msgSuccess("订单添加成功")
        this.open = false
        this.getList()
        this.submitting = false // 重置提交状态
        return
      }
      
      // 确保参数格式与后端实体类OrderItem匹配
      const addPromises = this.orderItems.map((item, index) => {
        // 确保所有必填字段都有有效值
        if (!orderId || !item.productId || !item.quantity || item.quantity <= 0 || !item.sellingPrice) {
          throw new Error(`商品${index + 1}数据不完整或无效，无法添加`)
        }
        
        // 确保参数类型正确
        const itemData = {
          orderId: Number(orderId),
          productId: Number(item.productId),
          sellingPrice: String(item.sellingPrice),
          quantity: Number(item.quantity)
        }
        
        // 进一步检查参数的有效性
        if (!Number.isInteger(itemData.orderId) || !Number.isInteger(itemData.productId) || 
            !Number.isInteger(itemData.quantity) || itemData.quantity <= 0 || 
            (typeof itemData.sellingPrice !== 'string' && typeof itemData.sellingPrice !== 'number')) {
          throw new Error(`商品${index + 1}参数类型无效，无法添加`)
        }
        
        return addItem(itemData).then(response => {
          // 更灵活地检查响应状态
          if (response && (response.code === 200 || response.code === '200')) {
            // 成功添加商品
          } else {
            throw new Error(`添加响应异常: ${JSON.stringify(response)}`)
          }
          return response
        }).catch(error => {
          // 仍然抛出错误，保持Promise.all的行为
          throw error
        })
      })
      
      // 首先尝试使用与后端实体类匹配的参数格式添加商品明细
      Promise.all(addPromises).then(results => {
        this.$modal.msgSuccess("订单添加成功")
        this.open = false
        this.getList()
      }).catch(error => {
        // 如果添加失败，显示错误
        let errorMessage = "订单已创建，但商品明细添加失败，请手动添加商品"
        if (error && error.message) {
          if (error.message.includes('timeout') || error.message.includes('网络错误')) {
            errorMessage = "网络连接超时，订单可能已创建，请刷新列表确认"
          } else if (error.message.includes('404')) {
            errorMessage = "API接口不存在，请检查系统配置"
          } else if (error.message.includes('500')) {
            errorMessage = "服务器内部错误，请联系管理员"
          } else if (error.message.includes('403')) {
            errorMessage = "权限不足，无法添加商品明细"
          } else if (error.message.includes('数据不完整')) {
            errorMessage = error.message
          } else if (error.message.includes('Cannot insert')) {
            errorMessage = '无法插入商品明细数据，可能是参数格式不匹配'
          }
        }
        
        this.$modal.msgError(errorMessage)
        // 立即关闭弹窗并刷新列表，让用户可以看到已创建的订单
        setTimeout(() => {
          this.open = false
          this.getList()
        }, 1000)
      }).finally(() => {
        // 确保无论成功失败都重置提交状态
        this.submitting = false
      })
    },
    /** 获取状态按钮类型 */
    getStatusButtonType(status) {
      switch (status) {
        case 1: return 'danger'; // 待付款-红色
        case 2: return 'primary'; // 已付款-蓝色
        case 3: return 'warning'; // 已发货-橙色
        case 4: return 'success'; // 完成-绿色
        default: return 'default';
      }
    },
    
    /** 获取状态文本 */
    getStatusText(status) {
      switch (status) {
        case 1: return '待付款';
        case 2: return '已付款';
        case 3: return '已发货';
        case 4: return '完成';
        default: return '未知状态';
      }
    },
    
    /** 切换订单状态 */
    toggleOrderStatus(row) {
      // 如果订单状态已经是完成，不执行任何操作
      if (row.status === 4) {
        return;
      }
      
      // 确定下一个状态（1→2→3→4→1循环）
      let nextStatus = row.status + 1;
      if (nextStatus > 4) {
        nextStatus = 1;
      }
      
      // 确认操作
      this.$modal.confirm(`确定将订单[${row.orderNo}]的状态从'${this.getStatusText(row.status)}'修改为'${this.getStatusText(nextStatus)}'吗？`).then(() => {
        // 调用更新API
        updateOrder({ id: row.id, status: nextStatus }).then(() => {
          this.$modal.msgSuccess('状态更新成功');
          // 刷新列表
          this.getList();
        }).catch(() => {
          this.$modal.msgError('状态更新失败');
        });
      }).catch(() => {});
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除销售单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
  
  <style scoped>
    .product-search-section {
      margin-top: 20px;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 5px;
    }
    
    .search-result {
      margin-top: 10px;
      padding: 10px;
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }
    
    .product-list-section {
      margin-top: 20px;
    }
    
    .product-list-section h4 {
      margin: 0 0 10px 0;
      color: #303133;
      font-weight: 500;
    }
    
    .no-data {
      text-align: center;
      color: #909399;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }
    
    /* 调整对话框宽度以适应商品列表 */
  .el-dialog--500px {
    width: 700px !important;
  }
  </style>
